package com.czkj.hwz.decorate.Activity;

import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.czkj.hwz.decorate.R;
import com.czkj.hwz.decorate.adapter.WorkerAdapter;
import com.czkj.hwz.decorate.base.HttpUrl;
import com.czkj.hwz.decorate.bean.Enterprise;
import com.czkj.hwz.decorate.bean.MyTab;
import com.czkj.hwz.decorate.bean.Worker;
import com.czkj.hwz.decorate.bean.WorkerType;
import com.czkj.hwz.decorate.bean1.ExamineEnterprise;
import com.czkj.hwz.decorate.bean1.User;
import com.google.gson.Gson;
import com.king.base.BaseActivity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import cn.finalteam.okhttpfinal.HttpCycleContext;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.JsonHttpRequestCallback;
import cn.finalteam.okhttpfinal.RequestParams;
import okhttp3.Headers;

/**
 * 工人分类页面
 * @author lxm
 * created at 2017/10/26 9:46
 */
public class WorkerClassifyActivity extends BaseActivity implements HttpCycleContext {
    private static final String TAG = "WorkerClassifyActivity";
    protected final String HTTP_TASK_KEY = "HttpTaskKey_" + hashCode();
    private LinearLayout ll_h;
    private LinearLayout ll;
    private TextView tv_qb;
    private GridView gv_qb;
    private MyTab mMyTab_v,mMyTab_h;
    private List<WorkerType> workerTypeLists;
    private List<Enterprise> enterpriseList;
    private List<Worker> workerList;
    private List<ExamineEnterprise> examineEnterpriseList;
    private List<User> userList;
    private int enterpriseid,workertypeid;
    private WorkerAdapter workerWorkerAdapter;
    private Handler handler=new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    ll.removeAllViews();
                    mMyTab_v.setData(workerTypeLists);
                    ll.addView(mMyTab_v.getView());
                    mMyTab_v.setText_Qb(tv_qb);
                    break;
                case 1:
                    ll_h.removeAllViews();
                    mMyTab_h.setData(enterpriseList);
                    ll_h.addView(mMyTab_h.getView());
                    enterpriseid=enterpriseList.get(0).getId();
                    getWorkerDataList(enterpriseid,workertypeid);
                    if (mMyTab_h!=null) {
                        mMyTab_h.changeColor(0);
                    }
                    break;
                case 2:
                    workerWorkerAdapter.notifyDataSetChanged();
                    dismissProgressDialog();
                    break;
            }
        }
    };

    private void getWorkerDataList(int enterpriseid,int workertypeid) {
        showProgressDialog();
        RequestParams params=new RequestParams(this);
        params.addFormDataPart("enterpriseid",enterpriseid);
        params.addFormDataPart("workertypeid",workertypeid);
        HttpRequest.get(HttpUrl.WORKER_DATAGRID,params,new JsonHttpRequestCallback(){
            @Override
            protected void onSuccess(JSONObject jsonObject) {
                super.onSuccess(jsonObject);
                parseWorkerData(jsonObject);
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                super.onFailure(errorCode, msg);
            }

            @Override
            public void onResponse(String response, Headers headers) {
                super.onResponse(response, headers);
            }
        });
    }

    private void parseWorkerData(JSONObject jsonObject) {
        workerList.clear();
        examineEnterpriseList.clear();
        userList.clear();
        JSONArray jsonArray=jsonObject.getJSONArray("rows");
        for (int i=0;i<jsonArray.size();i++) {
            JSONObject jsonObject1=jsonArray.getJSONObject(i);

            Gson gson=new Gson();
            Worker worker=gson.fromJson(jsonObject1.toJSONString(),Worker.class);
            JSONObject jsonObject2 = jsonObject1.getJSONObject("ExamineEnterprise");
            JSONObject jsonObject3 = jsonObject1.getJSONObject("User");
            ExamineEnterprise examineEnterprise=gson.fromJson(jsonObject2.toJSONString(),ExamineEnterprise.class);
            User user=gson.fromJson(jsonObject3.toJSONString(),User.class);
            Log.d(TAG, "parseWorkerData: "+worker.toString());
            Log.d(TAG, "parseWorkerData: "+jsonObject2.toString());
            Log.d(TAG, "parseWorkerData: "+jsonObject3.toString());
            workerList.add(worker);
            examineEnterpriseList.add(examineEnterprise);
            userList.add(user);
        }
        handler.sendEmptyMessage(2);
    }

    @Override
    public void initUI() {
        if (Build.VERSION.SDK_INT >= 21){
            Window window = getWindow();
            //取消设置透明状态栏,使 ContentView 内容不再覆盖状态栏
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            //设置状态栏颜色
            window.setStatusBarColor(getResources().getColor(R.color.yellow));
            getSupportActionBar().hide();
        }
        setContentView(R.layout.activity_worker_classify);
        workertypeid=-1000;
        ll_h=findView(R.id.ll_h);
        ll=findView(R.id.ll);
        gv_qb=findView(R.id.gv_qb);
        tv_qb=findView(R.id.tv_qb);
        workerTypeLists=new ArrayList<>();
        enterpriseList=new ArrayList<>();
        workerList=new ArrayList<>();
        examineEnterpriseList=new ArrayList<ExamineEnterprise>();
        userList=new ArrayList<User>();
        workerWorkerAdapter=new WorkerAdapter(context,workerList);
        mMyTab_v=new MyTab(this,LinearLayout.VERTICAL) {
            @Override
            public void onItemClickListener(int poistion) {
                workertypeid=workerTypeLists.get(poistion).getId();
                getWorkerDataList(enterpriseid,workertypeid);
            }
        };
        mMyTab_h=new MyTab(this,LinearLayout.HORIZONTAL) {
            @Override
            public void onItemClickListener(int poistion) {
                enterpriseid=enterpriseList.get(poistion).getId();
                getWorkerDataList(enterpriseid,workertypeid);
            }
        };

        gv_qb.setAdapter(workerWorkerAdapter);
        gv_qb.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent=new Intent(context,WorkerDetailActivity.class);
                intent.putExtra("workerList", (Serializable) workerList);
                intent.putExtra("examineEnterpriseList", (Serializable) examineEnterpriseList);
                intent.putExtra("userList", (Serializable) userList);
                intent.putExtra("position",position);
                startActivity(intent);
            }
        });
    }

    @Override
    public void initData() {
        getWorkerTypeList();
        getOperationCenter();
    }
    private void getWorkerTypeList() {
        RequestParams params=new RequestParams(this);
        HttpRequest.get(HttpUrl.WORKER_TYPE,params,new JsonHttpRequestCallback(){
            @Override
            protected void onSuccess(JSONObject jsonObject) {
                super.onSuccess(jsonObject);
                parseTypelistJson(jsonObject);
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                super.onFailure(errorCode, msg);
            }

            @Override
            public void onResponse(String response, Headers headers) {
                super.onResponse(response, headers);
            }
        });
    }
    private void getOperationCenter() {
        RequestParams params=new RequestParams(this);
        params.addFormDataPart("longitude","119");
        params.addFormDataPart("latitude","33");
        params.addFormDataPart("areacode","");
        HttpRequest.get(HttpUrl.ENTERPRISE_NEARBY,params,new JsonHttpRequestCallback(){
            @Override
            protected void onSuccess(JSONObject jsonObject) {
                super.onSuccess(jsonObject);
                parseOperationCenterJson(jsonObject);
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                super.onFailure(errorCode, msg);
            }

            @Override
            public void onResponse(String response, Headers headers) {
                super.onResponse(response, headers);
            }
        });
    }

    private void parseOperationCenterJson(JSONObject jsonObject) {
        enterpriseList.clear();

        JSONArray jsonArray=jsonObject.getJSONArray("result");
        for (int i=0;i<jsonArray.size();i++) {
            JSONObject jsonObjec1=jsonArray.getJSONObject(i);
            Gson gson=new Gson();
            Enterprise enterprise=gson.fromJson(jsonObjec1.toJSONString(),Enterprise.class);
            Log.d(TAG, "parseOperationCenterJson: "+enterprise.toString());
            Log.d(TAG, "parseOperationCenterJson: "+enterprise.getId());
            enterpriseList.add(enterprise);

        }
        handler.sendEmptyMessage(1);
    }

    private void parseTypelistJson(JSONObject jsonObject) {
        workerTypeLists.clear();
        JSONArray jsonArray=jsonObject.getJSONArray("result");
        for (int i=0;i<jsonArray.size();i++) {
            JSONObject jsonObject1=jsonArray.getJSONObject(i);
            Gson gson=new Gson();
            WorkerType workType=gson.fromJson(jsonObject1.toJSONString(),WorkerType.class);
            Log.d(TAG, "parseJson: "+workType.toString());
            Log.d(TAG, "parseJson: "+workType.getId());
            workerTypeLists.add(workType);

        }
        handler.sendEmptyMessage(0);
    }
    @Override
    public void addListeners() {

    }
    public void OnClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_qb:
                tv_qb.setTextColor(WorkerClassifyActivity.this.getResources().getColor(R.color.yellow));
                mMyTab_v.changeColor(-1);
                workertypeid=-1000;
                getWorkerDataList(enterpriseid,workertypeid);
                break;
            case R.id.iv_search:
                Intent intent=new Intent(context,WorkerSearchActivity.class);
//                if (workerTypeLists.get(0).getName().equals("全部工种")) {
//
//                }else {
//                    WorkerType workerType=new WorkerType();
//                    workerType.setName("全部工种");
//                    workerType.setId(-1000);
//                    workerTypeLists.add(0,workerType);
//                }
//                intent.putExtra("workerTypeLists", (Serializable) workerTypeLists);
//                MyApp myApp= (MyApp) getApplication();
//                myApp.setWorkerTypeLists(workerTypeLists);
                startActivity(intent);
                break;
        }
    }

    @Override
    public String getHttpTaskKey() {
        return HTTP_TASK_KEY;
    }
}
